package com.cloudtec.yunzonedep.modules.user.controller;


import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.cloudtec.yunzonedep.common.entity.ConstantPool;
import com.cloudtec.yunzonedep.common.entity.Result;
import com.cloudtec.yunzonedep.common.util.JWTUtil;
import com.cloudtec.yunzonedep.common.util.PasswordUtil;
import com.cloudtec.yunzonedep.common.util.RedisUtil;
import com.cloudtec.yunzonedep.modules.user.entity.SysUser;
import com.cloudtec.yunzonedep.modules.user.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author peter
 * @since 2019-12-13
 */
@RestController

public class LoginController {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private RedisUtil redisUtil;

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Result login(@RequestParam("username") String username,
                        @RequestParam("password") String password,
                        HttpServletResponse response){
        Result<String> result= new Result<String>();
        //1. 校验用户是否有效
        SysUser sysUser = sysUserService.getUserByName(username);
        if (sysUser == null) {
            result.error500("该用户不存在，请联系管理员");
            return result;
        }
        //2.检测用户是否已注销
        if ("0".equals(sysUser.getDelFlag())) {
            result.error500("该用户已注销");
            return result;
        }
        //3.检测用户是否已经被冻结
        if ("0".equals(sysUser.getStatus())) {
            result.error500("该用户已冻结");
            return result;
        }
        //2. 校验用户名或密码是否正确
        String userpassword = PasswordUtil.encrypt(password,sysUser.getSalt());
        if (userpassword.equals(sysUser.getPassword())) {
            String syspassword = sysUser.getPassword();
            // 生成token
            String token = JWTUtil.sign(username, syspassword);
            // 设置token缓存有效时间
            String key=username+ ConstantPool.LOGINTAG+token;
            redisUtil.set(key, token);
            redisUtil.expire(key, JWTUtil.EXPIRE_TIME / 1000);
            result.setToken(token);
            response.setHeader("Authorization",token);
            result.success("登录成功！");
        }else{
            result.error500("用户名或密码错误");
            return result;
        }


        return  result;
    }

    @GetMapping("/403")
    public Result<?> noauth()  {
        return Result.error("没有权限，请联系管理员授权");
    }

}

